
import Vue from 'vue'
import Vuex from 'vuex'
import { Login } from '../api/user'
import router from '../router/index'
Vue.use(Vuex)

const userInfo = window.localStorage.getItem('userInfo')
const token = window.localStorage.getItem('token')
const yzm = window.localStorage.getItem('Yzm')
const cinemas = JSON.parse(window.localStorage.getItem('cinemas'))

export default new Vuex.Store({
  state: {
    userInfo: userInfo || null, // 代码的三目运算简写形式，不这样写会报错
    token: token || null,
    yzm: yzm || null,
   
  },
  mutations: {
    LOGIN (state, payload) {
      state.userInfo = payload.userInfo
      state.token = payload.token
    },
    setYzm (state, yzm) {
      state.yzm = yzm
    },
    sinOut (state) {
      state.userInfo = null
      state.token = null
    },
  
  },
  actions: {
    loginAsync ({ commit }, payload) {
      Login(payload).then(res => {
        console.log(res)
        let result = res.data
        if (result.code === 0) {
          // 登录成功
          // 将数据写入到仓库中
          commit('LOGIN', result.data)
          // 本地存储一份数据
          window.localStorage.setItem('userInfo', JSON.stringify(result.data.userInfo))
          window.localStorage.setItem('token', result.data.token)
          // 跳转会center页面(使用编程式导航)this.$router,但要注意在vuex中this不是实列对象，没有$router对象
          // 在当前文件直接将router文件引入进来
          router.replace('my')
        } else {
          // 登录失败
          alert(result.msg)
        }
      })
    }
  }
})
